import re,os
from Blocks import *
from Utilities import *

word = re.compile('[\\w\n]')
onlyWords = re.compile('\\w')

def parseDocument(documentLocation,outputDir,templateDir):
    doc = open(documentLocation,'r')
    
    codeTemplateFile = open(os.path.join(templateDir,'codeBlock.html'),'r')
    commentTemplateFile = open(os.path.join(templateDir,'commentBlock.html'),'r')
    
    codeTemplate = codeTemplateFile.read();
    commentTemplate = commentTemplateFile.read();
    
    codeTemplateFile.close()
    commentTemplateFile.close()

    document = CodeDocument();
    currentBlock = None
    
    for docLine in doc.readlines():
        if (not word.search(docLine) ):
            continue
        if (docLine == '\n'):
            currentBlock.addLine(docLine)
            continue
        isComment = 0
        line = ""
        if (docLine[0] == "#"):
            isComment = 1
        if (isComment and type(currentBlock) != type(CommentBlock(None))):
            document.addBlock(currentBlock)
            currentBlock = CommentBlock(commentTemplate)
        elif (not isComment and type(currentBlock) != type(CodeBlock(None,None))):
            document.addBlock(currentBlock)
            currentBlock = CodeBlock(outputDir,codeTemplate)

        docLine = docLine.replace('\n','')
        if (isComment):
            line = docLine[1:(len(docLine))]
        else:
            line = docLine

        print "Line: "+line
        currentBlock.addLine(line)

    document.addBlock(currentBlock)

    doc.close()

    return document

def generateOutputFile(document, title, outputDir, outputName, templateDir):
    templateFile = open(os.path.join(templateDir,'template.html'),'r')
    template = templateFile.read()
    templateFile.close()

    template = template.replace('{rpub_title}',title)

    docString = document.toString()
    tmpFiles = document.tmpFiles

    for tmpFile in tmpFiles:
        os.system('mv '+tmpFile+' '+os.path.join(outputDir,tmpFile))
    
    template = template.replace('{rpub_body}',docString)

    newDoc = open(os.path.join(outputDir,outputName),'w')
    newDoc.write(template);
    newDoc.close()

def setupOutputDirectory(outputDir,templateDir):
    removeall(outputDir)
    
    filesToCopy = []
    if (os.path.exists(os.path.join(templateDir,'include.rpub'))):
        includeHandle = open(os.path.join(templateDir,'include.rpub'),'r')
        for line in includeHandle.readlines():
            line = line.replace('\n','')
            print 'Looking for: ('+os.path.join(templateDir,line)+')'
            if (os.path.exists(os.path.join(templateDir,line))):
                filesToCopy.append(os.path.join(templateDir,line))
            else:
                raise NameError, 'Could not find file: '+line
        
    for file in filesToCopy:
        command = 'cp '+file+' '+outputDir
        os.system(command);

loc = '/Users/thatcherclay/Workbench/RPub/test/Basic.R'
outputDir = '/Users/thatcherclay/Workbench/RPub/samples'

tempDir ='/Users/thatcherclay/Workbench/RPub/templates/basicTemplate'
outputName = 'SampleRDocument.html'

setupOutputDirectory(outputDir,tempDir)
doc = parseDocument(loc,outputDir,tempDir)
generateOutputFile(doc, 'R Publication', outputDir, outputName, tempDir)
